#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include  "esp_err.h"
#include <string.h>
#include "esp_sntp.h"
#include "esp_netif_sntp.h"
#include "uart_cmd.h"
#include "RTC.h"
#include "driver/uart.h"
#include "wifi.h"

char* wificonnect_pic = "main.p0.pic=0\xff\xff\xff";
char* wifidisconnect_pic = "main.p0.pic=10\xff\xff\xff";

time_t current_get;  // 定义一个time_t变量current_get
struct tm info_get; // 定义一个tm结构体变 info_get

void obtain_time(void)
{
	// Set timezone to Beijing time
	setenv("TZ", "CST-8", 1); // CST-8 represents China Standard Time (UTC+8)
	tzset();

	esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("cn.pool.ntp.org");
	config.renew_servers_after_new_IP = true,

	// Initialize SNTP with the provided configuration
	esp_netif_sntp_init(&config);

	// Start SNTP
	esp_netif_sntp_start();

	// wait for time to be set
	time_t now = 0;
	struct tm timeinfo = {0};
	int retry = 0;
	const int retry_count = 15;
	while (esp_netif_sntp_sync_wait(2000 / portTICK_PERIOD_MS) == ESP_ERR_TIMEOUT && ++retry < retry_count)
	{

	}
	time(&now);
	localtime_r(&now, &timeinfo);
    timeinfo.tm_mon++;

    // Print current time
	char strftime_buf[64];
	strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
    
    now = mktime(&timeinfo);  // 将tm结构体转换为time_t格式
    struct timeval tv = { .tv_sec = now };  // 定义一个timeval结构体变量tv，并设置其秒数
    settimeofday(&tv, NULL);  // 设置系统时间
}


void wifi_event_handle(void* event_handler_arg,esp_event_base_t event_base,int32_t event_id,void* event_data)
{
    if(event_base == WIFI_EVENT) //WiFi事件类型
    {
        switch (event_id)
        {
        case WIFI_EVENT_STA_START:
            esp_wifi_connect();
            break;
        
        case WIFI_EVENT_STA_CONNECTED:
            ESP_LOGI(TAG,"esp32 connected to ap!");
            uart_write_bytes(SCREEN_UART,wificonnect_pic,strlen(wificonnect_pic));
            break;
        
        case WIFI_EVENT_STA_DISCONNECTED:
            esp_wifi_connect();
            ESP_LOGI(TAG,"esp32 connected the ap fail! retry!");
            uart_write_bytes(SCREEN_UART,wifidisconnect_pic,strlen(wifidisconnect_pic));
            break;
        default:
            break;
        }
    }
    else if(event_base == IP_EVENT)//IP事件类型
    {
         switch (event_id)
         {
            case IP_EVENT_STA_GOT_IP:
                ESP_LOGI(TAG,"esp32 get ip address");
                uart_write_bytes(SCREEN_UART,wificonnect_pic,strlen(wificonnect_pic));
                obtain_time();
                break;
         }
    }
}


void wifi_init()
{
    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init()); //初始化TCP IP协议 
    ESP_ERROR_CHECK(esp_event_loop_create_default());//创建事件系统循环
    esp_netif_create_default_wifi_sta();//创建STA
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    esp_event_handler_register(WIFI_EVENT,ESP_EVENT_ANY_ID,wifi_event_handle,NULL);//注册回调函数(wifi事件)
    esp_event_handler_register(IP_EVENT,IP_EVENT_STA_GOT_IP,wifi_event_handle,NULL);//网络事件,连接到路由器获取到IP地址后会触发

    wifi_config_t wifi_config = {
        .sta.threshold.authmode = WIFI_AUTH_WPA2_PSK, //加密模式
        .sta.pmf_cfg.capable = true,//启用保护管理帧
        .sta.pmf_cfg.required = false,//不启用与保护管理帧的设备进行通信
    };
    memset(&wifi_config.sta.ssid,0,sizeof(wifi_config.sta.ssid));
    memcpy(wifi_config.sta.ssid,TEST_SSID,strlen(TEST_SSID));

    memset(&wifi_config.sta.password,0,sizeof(wifi_config.sta.password));
    memcpy(wifi_config.sta.password,TEST_PASSWORD,strlen(TEST_PASSWORD));

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA,&wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());


}